package io.github.javpower.imagerex.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@Configuration
public class SecurityConfig {

    // ✅ 允许明文密码（仅测试用）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    // ✅ 内存用户
    @Bean
    public UserDetailsService userDetailsService() {
        return new InMemoryUserDetailsManager(
                User.withUsername("admin")
                        .password("jifu25")
                        .roles("ADMIN")
                        .build()
        );
    }



    // ✅ Spring Security 主配置
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorize -> authorize
                        .antMatchers("/api/image/upload/**").hasRole("ADMIN")
                        .antMatchers("/actuator/**").permitAll()
                        .anyRequest().permitAll()
                )
//                .addFilterBefore(negotiateSecurityFilter(), BasicAuthenticationFilter.class)
//                .addFilterAfter(new WaffleToSpringAuthBridgeFilter(), NegotiateSecurityFilter.class)
//                .exceptionHandling()
//                .authenticationEntryPoint(negotiateSecurityFilterEntryPoint())
//                .and()
//                .formLogin().disable()
                .formLogin(form -> form
                        .loginPage("/login")
                        .defaultSuccessUrl("/?image=1", true)
                        .permitAll()
                )
                .logout(LogoutConfigurer::permitAll)
                .httpBasic(Customizer.withDefaults())
                .csrf(csrf -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                );

        return http.build();
    }
}
